<template>
  <el-cascader ref="cascader" size="small" :props="prop" expandTrigger="hover" :show-all-levels="false" @change="handleChange" :value="areaName" />
</template>

<script>
import { getSessionStorage } from "@/common/js/storage";
import { $budgetAPI } from "@/api";
export default {
  props: {
    maxLevel: {
      type: Number,
      default: Infinity,
    },
    area_name: {
      type: String,
      default: ""
    },
    area_id: {
      type: String | Number,
      default: ""
    }
  },
  // created(){
  //   $budgetAPI.getCompanyByLvl({
  //     areaId: this.accountInfo.areaId,
  //     lvl: 1
  //   })
  // },
  data() {
    var that = this;
    let accountInfo = JSON.parse(getSessionStorage("accountInfo"));
    return {
      areaName: '',
      id: "",
      lvl: "",
      accountInfo,
      prop: {
        lazy: true,
        checkStrictly: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          var areaId;
          var lvl;
          var areaName;
          if (level == 0) {
            areaId = accountInfo.areaId;
            areaName = accountInfo.areaName;
            lvl = accountInfo.areaLvl;
            resolve([{ value: areaName, label: areaName, lvl: lvl, areaId }]);
          } else {
            if (level >= that.maxLevel) {
              resolve([]);
              return;
            }
            areaId = node.data.areaId;
            lvl = node.data.lvl;
            $budgetAPI.getCompanyByLvl(
              {
                areaId,
                lvl: lvl,
              },
              (res) => {
                if (res.code == 0) {
                  let nodes = res.content.map((item, index) => {
                    return {
                      value: item.areaName,
                      label: item.areaName,
                      lvl: item.areaLvl !== lvl ? item.areaLvl : "",
                      areaId: item.areaId
                    };
                  });
                  resolve(nodes);
                } else {
                  that.alertError(res);
                }
              }
            );
          }
        },
      },
    };
  },
  methods: {
    handleChange() {
      let data = this.$refs.cascader.getCheckedNodes()[0].data;
      this.$emit("update:area_name", data.value);
      this.$emit("update:area_id", data.areaId);
      this.$refs.cascader.dropDownVisible = false;
    },
  },
};
</script>

<style lang="scss">
</style>
